package pers.sloera.leetcode.groupAnagrams;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @author SloeraN
 * @version 1.0
 * @class pers.sloera.leetcode.groupAnagrams.Solution
 * @date 2020/12/14
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}));
    }

    /**
     * 字母异位词分组
     * <p>
     * 如为同类，则所属字符排序后应保持一致。将排序后的值作为key，用于归类
     *
     * @param strs 待分类数组
     * @return java.util.List<java.util.List < java.lang.String>> 每类异位词为一个list
     * @date 2020/12/14
     */
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String, ArrayList<String>> keyGroup = new HashMap<>(strs.length);
        for (String str : strs) {
            char[] tempArray = str.toCharArray();
            Arrays.sort(tempArray);
            // 异位词排序后 key 一致
            String string = new String(tempArray);
            if (keyGroup.containsKey(string)) {
                keyGroup.get(string).add(str);
            } else {
                ArrayList<String> value = new ArrayList<>();
                value.add(str);
                keyGroup.put(string, value);
            }
        }
        return keyGroup.values().stream().collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
    }
}
